<?php

namespace App\Domain\Dict\Services;

use App\Domain\Dict\Dao\DictDao;
use App\Exceptions\BadRequestException;

class DictService
{
    public function findByTypeCode($param)
    {
        $dictDao = new DictDao();
        $data['list'] = $dictDao->findByTypeCode($param);
        return $data;
    }

    public function setDictType($param)
    {
        $dictDao = new DictDao();
        if ($param['id']) {
            $dictType = $dictDao->findByType($param['id']);
            if ($dictType) {
                $res = [
                    'name' => $param['name'],
                    'info' => $param['info'],
                ];
                $dictType = $dictDao->updateType($dictType, $res);
            }
        } else {
            $dictType = $dictDao->findByTypeName($param['name']);
            if ($dictType['name'] == $param['name']) {
                throw new BadRequestException('类别已存在');
            }
            $data = $dictDao->findNew();
            $code = $data['code'] + 1;
            $dictType = $dictDao->createType([
                'name' => $param['name'],
                'info' => $param['info'],
                'code' => $code
            ]);
        }
        return $dictType;
    }

    public function setDict($param)
    {
        $dictDao = new DictDao();
        if ($param['id']) {
            $dict = $dictDao->findByDictId($param['id']);
            if ($dict) {
                $res = [
                    'name' => $param['name'],
                    'info' => $param['info'],
                    'type_code' => $param['type_code'],
                    'code' => $param['code'],
                ];
                $dict = $dictDao->update($dict, $res);
            }
        } else {
            $dict = $dictDao->create([
                'name' => $param['name'],
                'info' => $param['info'],
                'type_code' => $param['type_code'],
                'code' => $param['code'],
            ]);
        }
        return $dict;
    }


    public function updateType($material_dict_code)
    {
        $dictDao = new DictDao();
        $dict = $dictDao->findByMaterialCode($material_dict_code);
        if (empty($dict)) {
            throw new BadRequestException('类别不存在');
        }
        $data = [
            'name' => $param['name'],
        ];
        $dict = $dictDao->update($dict, $data);
        return $dict;
    }


}
